import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios';

// 创建axios实例
const instance: AxiosInstance = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 创建一个Map来存储取消令牌
const cancelTokenMap = new Map<string, CancelTokenSource>();

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在这里可以添加token等全局请求头
    const token = localStorage.getItem('token');
    if (token) {
      config.headers = config.headers || {};
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 清理已完成的请求记录
    const url = response.config.url;
    if (url && cancelTokenMap.has(url)) {
      cancelTokenMap.delete(url);
    }

    // 在这里处理全局响应逻辑
    // HTTP状态码（如200, 401, 500）表示请求的传输层状态
    // 业务状态码（如code: 0, 1, 2）表示具体的业务逻辑状态
    // if (response.data.code !== 0) {
    //   return Promise.reject(response.data);
    // }
    return response.data;
  },
  (error) => {
    // 清理失败的请求记录
    const url = error.config?.url;
    if (url && cancelTokenMap.has(url)) {
      cancelTokenMap.delete(url);
    }

    // 在这里处理全局错误
    if (error.response?.status === 401) {
      // 处理未授权
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 封装请求方法
const http = {
  get: <T>(url: string, config?: AxiosRequestConfig & { baseURL?: string }): Promise<T> => {
    const source = axios.CancelToken.source();
    cancelTokenMap.set(url, source);
    return instance.get(url, { 
      ...config,
      baseURL: config?.baseURL || '/wx',
      cancelToken: source.token 
    });
  },
  post: <T>(url: string, data?: any, config?: AxiosRequestConfig & { baseURL?: string }): Promise<T> => {
    const source = axios.CancelToken.source();
    cancelTokenMap.set(url, source);
    return instance.post(url, data, { 
      ...config,
      baseURL: config?.baseURL || '/wx',
      cancelToken: source.token 
    });
  },
  put: <T>(url: string, data?: any, config?: AxiosRequestConfig & { baseURL?: string }): Promise<T> => {
    const source = axios.CancelToken.source();
    cancelTokenMap.set(url, source);
    return instance.put(url, data, { 
      ...config,
      baseURL: config?.baseURL || '/wx',
      cancelToken: source.token 
    });
  },
  delete: <T>(url: string, config?: AxiosRequestConfig & { baseURL?: string }): Promise<T> => {
    const source = axios.CancelToken.source();
    cancelTokenMap.set(url, source);
    return instance.delete(url, { 
      ...config,
      baseURL: config?.baseURL || '/wx',
      cancelToken: source.token 
    });
  },
  // 添加取消请求的方法
  // http.cancelRequest('/api/some-endpoint');
  cancelRequest: (url: string) => {
    const source = cancelTokenMap.get(url);
    if (source) {
      source.cancel(`Request canceled: ${url}`);
      cancelTokenMap.delete(url);
    }
  },
  // 取消所有请求
  cancelAllRequests: () => {
    cancelTokenMap.forEach((source, url) => {
      source.cancel(`Request canceled: ${url}`);
      cancelTokenMap.delete(url);
    });
  },
};

export default http;
